package com.tanhua.autoconfig.template;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.tanhua.autoconfig.properties.CosProperties;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class CosTemplate {

    private CosProperties properties;

    public CosTemplate(CosProperties properties) {
        this.properties = properties;
    }

    public String upload(File imageFile, String filename) {
//        File localFile = new File(filename);
        filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
        // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
        COSCredentials cred = new BasicCOSCredentials(properties.getAccessKey(), properties.getSecretKey());
        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(properties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 指定要上传的文件
//        File localFile = new File(filename);
        // 指定文件 将要存放的存储桶
        String bucketName = "lihei-1302458974";
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String domain = "https://lihei-1302458974.cos.ap-guangzhou.myqcloud.com/";

//        String key = "folder/picture.jpg";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, imageFile);
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown();

        String url = domain + filename;
        System.out.println(url);
        return url;
    }
}
